package com.live.stamp.base.token;

import com.hikeSoft.common.utils.BaseUtils;
import com.live.stamp.base.constants.Constants;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 */
public class TokenUtil {

    private static final String key= "STAMP.2018.04.12-yyyy-mm-dd";

    public static String buildToken(final String salt, final int exp) {
        Date expDate= BaseUtils.strToDate(BaseUtils.addHour(BaseUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"), exp),"yyyy-MM-dd HH:mm:ss");
        return Jwts.builder().setSubject(salt).setExpiration(expDate).signWith(SignatureAlgorithm.HS512, key).compact();
    }

    public static String buildToken(final String salt) {
        return buildToken(salt, Constants.DEFAULT_EXP);
    }

    public static void clearToken(String tk) {
        tk = null;
        new UserModelUtil(null);
    }

    public static String parseToken (final String token) {
        String out;
        try {
            out = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
        } catch (ExpiredJwtException e) {
            out = Constants.TOKEN_ERROR_EXP;
        } catch (UnsupportedJwtException e) {
            out = Constants.TOKEN_ERROR_SIGN;
        } catch (MalformedJwtException e) {
            out = Constants.TOKEN_ERROR_STR;
        } catch (SignatureException e) {
            out = Constants.TOKEN_ERROR_SIGN;
        } catch (IllegalArgumentException e) {
            out = Constants.TOKEN_ERROR_STR;
        }
        return out;
    }


    public static void main(String[] args) {
        System.out.println(TokenUtil.buildToken("1"));
    }

}
